<template>
	<el-col :span="24" class="All">
		<el-col :span="24" class="TableInfo">
			<div class="serverContainer">
				<el-row :gutter="5">
					<el-col :span="4">
						<el-col :span="8" style="
                display: grid;
                align-items: center;
                font-size:15px
                height: 30px;
              ">请选择IP:</el-col>

						<el-col :span="16">
							<el-select v-model="selectItem" filterable placeholder="请输入ip" :loading="loading"
								@change="selectIp" ref="select">
								<!-- :remote-method="remoteMethod" remote reserve-keyword -->
								<el-option v-for="item in options" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-col>
					</el-col>
					<el-col :span="20">
						<v-historyToolBar :fullPath="postData.opera" @pickerDate="getPickerDate"
							@selectOpera="getSelectOpera" @intervalOpera="getIntervalOpera"
							@inputFilter="getInputFilter" @goSearch="getTableData" :operaOption.sync="operaOption"
							:tableData="tableData" :tableDataFields="tableDataFieldsFn" :IntervalOption="IntervalOption"
							:toolDisabled="loading" @exportData="exportData"
							@InitFileSystemHistory="InitFileSystemHistory"
							@ChangeFileSystemHistory="ChangeFileSystemHistory" :isShowfre="true" :fileName="fileName">
						</v-historyToolBar>
					</el-col>
				</el-row>

				<div class="netload">
					<transition name="server" mode="out-in">
						<v-HistServerCpuLoad v-loading="loading" element-loading-text="拼命加载中"
							element-loading-spinner="el-icon-loading" :allData="allData" :memoryData="memoryData"
							v-if="this.postData.opera == 'CpuUsageHistory'">
						</v-HistServerCpuLoad>
						<!-- <v-HistServerMemoryLoad v-loading="loading" element-loading-text="拼命加载中"
							element-loading-spinner="el-icon-loading" :allData="memoryData"
							v-if="this.postData.opera == 'CpuUsageHistory'">
						</v-HistServerMemoryLoad> -->
						<v-HistServerFileSystem v-loading="loading" element-loading-text="拼命加载中"
							element-loading-spinner="el-icon-loading" :allData="allData"
							v-if="this.postData.opera == 'FileSystemHistory'">
						</v-HistServerFileSystem>
					</transition>
				</div>
				<!-- <el-table
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading"
                    :data="tableData"
                    border
                    style="width: 100%">
                    <template v-for="(item) in tableColumns">
                        <el-table-column 
                            :prop="item.prop" 
                            :label="item.label"   
                            :width="item.width"
                            v-if="item.isShow"
                            :key="item.prop">
                            <template v-slot="scope">
                                <template v-if="item.format == 'progress'">
                                    <el-progress
                                        :percentage="Number(calcCheng(scope.row[item.prop], 100).toFixed(1))" 
                                        :color="TalallColorMethod">
                                    </el-progress> 
                                </template>
                                <template v-else-if="item.format == 'progress2'">
                                    <el-progress
                                        :percentage="scope.row[item.prop] == 100 ? Number(scope.row[item.prop].toFixed(0)) : Number(scope.row[item.prop].toFixed(1))" 
                                        :color="TalallColorMethod2">
                                    </el-progress> 
                                </template>
                                <template v-else-if="item.format == 'capacity'">
                                    <div>
                                        {{ scope.row[item.prop] }}&nbsp;GB
                                    </div>
                                </template>
                                <template v-else>
                                    <div>
                                        {{ scope.row[item.prop] }}
                                    </div>
                                </template>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
                <v-pagination
                    :dataTotal="dataTotal" 
                    :curPage="postData.curPage" 
                    :pageSize="postData.pageSize" 
                    @getCurPage="getPaginationCurPage"
                    @getPageSize="getPaginationPageSize">
                </v-pagination> -->
			</div>
		</el-col>

		<el-dialog title="请选择节点" :visible.sync="dialogVisible" width="30%" :show-close="false"
			:close-on-press-escape="false" :close-on-click-modal="false">
			<div style="width: 100%;display: flex;flex-direction: row;justify-content: center;">
				<el-select v-model="PreselectedValue" filterable placeholder="请选择IP,可输入进行搜索">
					<el-option v-for="item in columns" :key="item.IP" :label="item.selectName" :value="item.IP">
					</el-option>
				</el-select>
			</div>

			<!-- <div v-for="item in this.columns" :key="item.IP">
				<el-radio v-model="PreselectedValue" :label="item.IP">{{item.IP}}</el-radio>
			</div> -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="PreselectedValueDialogClose">取 消</el-button>
				<el-button type="primary" @click="PreselectedValueDialogSubmit">确 定</el-button>
			</span>
		</el-dialog>
	</el-col>
</template>

<script>
	import {
		fetchData,
		exportData,
		getFileMounted,
		getFileSystemHistory,
	} from "@/api/index.js";
	import vPagination from "common/Pagination.vue";
	import vHistoryToolBar from "historyData/HistoryToolBar.vue";
	import vHistServerCpuLoad from "historyData/servers/HistServerCpuLoad.vue";
	import vHistServerMemoryLoad from "historyData/servers/HistServerMemoryLoad.vue";
	import vHistServerFileSystem from "historyData/servers/HistServerFileSystem.vue";
	import downloadFile from "@/plugs/downloadFile.js";
	import dateFormat from "@/plugs/dateFormat.js";
	// import * as Api from '@/api/index';
	import axios from "axios";
	import {
		selectServerCpu,
		getHisoryDataForMemory
	} from "@/api/index";
	import tableColumns from "../exportExcel";

	export default {
		components: {
			vPagination,
			vHistoryToolBar,
			vHistServerCpuLoad,
			vHistServerMemoryLoad,
			vHistServerFileSystem,
		},

		data() {
			return {
				// postData: {
				// 	opera: '',
				// 	curPage: 1,
				// 	pageSize: 1000000,
				// 	filtersType: 'fuzzyquery',
				// 	filters: {

				// 	},
				// },
				fileName: "",
				tableColumns: tableColumns,
				postData: {
					opera: "",
					curPage: 1,
					pageSize: 1000000,
					filtersType: "fuzzyquery",
					filters: {
						monid: "",
						IP: "",
						StartTime: "",
						EndTime: "",
						fre: "",
						data: "",
					},
				},
				tableData: [],
				MtableData: [],
				CtableData: [],
				allData: {},
				memoryData: {},
				dataTotal: 0,
				selectItem: "",
				searchJson: {},
				restaurants: [],
				operaOption: [{
						label: "CPU和内存",
						value: "CpuUsageHistory",
						filter: ""
					},
					// {
					// 	label: "内存",
					// 	value: "MemoryUsageHistory",
					// 	filter: ""
					// },
					{
						label: "文件系统",
						value: "FileSystemHistory",
						filter: {
							mounted_on: "指定挂载点...",
							options: [],
							data: ""
						},
					},
				],
				IntervalOption: [{
						value: "1",
						label: "1分钟",
					},
					{
						value: "5",
						label: "5分钟",
					},
					{
						value: "10",
						label: "10分钟",
					},
					{
						value: "30",
						label: "30分钟",
					},
					{
						value: "60",
						label: "60分钟",
					},
					{
						value: "120",
						label: "120分钟",
					},
				],

				postSearchData: {
					opera: "hostconnect",
					curPage: 1,
					pageSize: 1000000,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "exclude",
					filters: {
						OS_TYPE: "Monitor",
					},
				},
				columns: [],
				TextDatabace: {},
				searchIP: "",
				dataTotal: 100,
				options: "",
				list: [],
				seleItem: {},
				loading: false,
				exportOption: {
					CpuUsageHistory: {
						url: "Sp/excMV_OS_CPU",
						fileName: "CPU使用率",
					},
					MemoryUsageHistory: {
						url: "Sp/excMV_OS_MEMORY",
						fileName: "内存使用率",
					},
					FileSystemHistory: {
						url: "Sp/excMV_os_filesystem",
						fileName: "文件系统使用率",
					},
				},
				dialogVisible: false,
				PreselectedValue: "",
			};
		},
		created() {
			this.getSearchData();
		},
		computed: {
			tableDataFieldsFn() {
				let _jsonfields = {};
				this.tableColumns.filter((item) => {
					if (item.isShow) {
						_jsonfields[item.label] = item.prop;
					}
				});

				return _jsonfields;
			},
		},
		mounted() {
			this.$refs.select.$el.onpaste = () => {
				// this.$message.error('禁止操作')
				return false;
			};
		},
		methods: {
			getSearchData() {
				fetchData({
					postSearchData: JSON.stringify(this.postSearchData),
				}).then((res) => {
					this.columns = res.data;
					this.columns.forEach((item, index) => {
						this.columns[index].selectName = item.IP + "/" + item.OS_TYPE
					})
					console.log(111, this.columns)
					this.list = this.columns.map((item) => {
						return {
							value: `${item.IP}`,
							label: `${item.IP}`,
						};
					});
					this.options = this.list;
					// 初始化时，选中第一个节点
					if (this.columns.length > 0) {
						// this.dbClickFirst();
						// this.getTableData();
						this.dialogVisible = true;
					}
				});
			},
			PreselectedValueDialogSubmit() {
				if (this.PreselectedValue) {
					this.dbClickFirst();
					this.$message.success("选择成功");
					this.dialogVisible = false;
				} else {
					this.$message.error("请选择IP");
				}
			},
			PreselectedValueDialogClose() {
				this.$router.go(-1);
				this.dialogVisible = false;
			},
			TalallColorMethod(percentage) {
				if (percentage <= 50) {
					return "#67c23a";
				} else if (percentage <= 75) {
					return "#e6a23c";
				} else {
					return "#f56c6c";
				}
			},
			TalallColorMethod2(percentage) {
				if (percentage <= 50) {
					return "#f56c6c";
				} else if (percentage <= 75) {
					return "#e6a23c";
				} else {
					return "#67c23a";
				}
			},
			handSearchIp(item) {
				this.postData.filters.IP = item.IP;
				this.seleItem = item;
				this.postData.filters.monid = item.MONID;

				// this.getTableData();
			},
			dbClickFirst() {
				let ThisColumns = this.columns.filter((item) => {
					return item.IP == this.PreselectedValue;
				});
				this.handSearchIp(...ThisColumns);
				// this.selectItem = this.columns[0].IP;
				this.selectItem = this.PreselectedValue;
				this.getTableData();
			},
			getTableData() {
				this.loading = true;
				//   fetchData({
				//     postData: JSON.stringify(this.postData),
				//   }).then((_) => {
				//     console.log(_);
				//   });
				// this.columns.forEach(_=>{
				// 		fetchData({
				//     postData: JSON.stringify({
				// 	opera: '',
				// 	curPage: 1,
				// 	pageSize: 1000000,
				// 	filtersType: 'fuzzyquery',
				// 	filters: {
				// 		monid: _.MONID,
				// 		IP: _.IP,
				// 		StartTime: '2008-07-27 00:00:00',
				// 		EndTime: '2021-07-27 00:00:00',
				// 		// fre: '',
				// 	},
				// },)
				// }).then(res=>{console.log(res,_.IP)})

				// })

				// Api.selectcpu({
				//     postData: JSON.stringify(this.postData)
				// })
				// .then((res) => {
				//     // this.allData = {};
				//     this.dataTotal = res.dataTotal;
				//     // this.tableData = res.data;
				//     this.allData = res;
				//     this.loading = false;
				// });
				// 处理postData

				// let data={
				//     time:this.postData.filters.StartTime,
				//     time2:this.postData.filters.EndTime,
				//     fre: this.postData.filters.fre,
				//     ip:'172.20.1.114'
				// }
				// Api.selectcpu({
				//      time:this.postData.filters.StartTime,
				//     time2:this.postData.filters.EndTime,
				//     fre: this.postData.filters.fre,
				//     ip:'172.20.1.114'
				// }

				// )

				if (this.postData.filters.IP != "") {
					switch (this.postData.opera) {
						case "CpuUsageHistory":
							selectServerCpu({
									time: this.postData.filters.StartTime,
									time2: this.postData.filters.EndTime,
									// fre: this.postData.filters.fre,
									ip: this.postData.filters.IP,
								})
								.then((res) => {
									this.allData = {
										USED: [],
										Time: [],
										user:[],
										system:[],
										wait:[],
									};
									// this.dataTotal = res.dataTotal;
									// this.tableData = res;
									// this.allData = res;

									if (res) {
										this.dataTotal = Object.keys(res)[0] * 1;
										this.allData.dataTotal = this.dataTotal;
										Object.values(res)[0].forEach((item) => {
											this.allData.USED.push(item.avgCpuUsed);
											this.allData.Time.push(item.recordTime);
											this.allData.user.push(item.avgCpuUser || '');
											this.allData.system.push(item.avgCpuSystem || '');
											this.allData.wait.push(item.avgCpuIowait || '');
										});
										this.allData.StartTime = this.postData.filters.StartTime;
										this.allData.EndTime = this.postData.filters.EndTime;
									}
									this.loading = false;
									this.CtableData = this.allData.USED.map((item, index) => {
										return {
											USED: this.allData.USED[index],
											Time: this.allData.Time[index],
											user: this.allData.user[index] || '',
											system: this.allData.system[index] || '',
											wait: this.allData.wait[index] || '',
										};
									});
								})
								.catch((err) => {
									console.log(err);
								});
							getHisoryDataForMemory({
									time: this.postData.filters.StartTime,
									time2: this.postData.filters.EndTime,
									// fre: this.postData.filters.fre,
									ip: this.postData.filters.IP,
								})
								.then((res) => {
									// this.allData = {};
									// this.dataTotal = res.dataTotal;
									// this.tableData = res;
									// this.allData = res;
									// this.loading = false;
									this.memoryData = {
										USED: [],
										Time: [],
									};
									if (res) {
										this.dataTotal = Object.keys(res)[0] * 1;
										this.memoryData.dataTotal = this.dataTotal;
										Object.values(res)[0].forEach((item) => {
											this.memoryData.USED.push(item.avgMemoryUsed);
											this.memoryData.Time.push(item.recordTime);
										});
									}
									this.loading = false;
									this.MtableData = this.memoryData.USED.map((item, index) => {
										return {
											USED1: this.memoryData.USED[index],
											Time1: this.memoryData.Time[index],
										};
									});

									console.log('内存', this.memoryData)
									console.log('CPU', this.CtableData)

									// const cupAndOs = [];
									// this.CtableData.forEach((cupItem, index) => {
									// 	const osItem = this.MtableData[index];
									// 	cupAndOs.push({
									// 		Ctime: cupItem.Time,
									// 		Cused: cupItem.USED,
									// 		Otime: osItem.Time1,
									// 		Oused: osItem.USED1
									// 	});
									// });
									// console.log(123456, cupAndOs)


									let arr1 = null
									let arr2 = null
									if (this.MtableData.length > this.CtableData.length) {
										arr1 = Array.from(this.MtableData)
										arr2 = Array.from(this.CtableData)
									} else {
										arr1 = Array.from(this.CtableData)
										arr2 = Array.from(this.MtableData)
									}
									for (let i in arr1) {
										for (let j in arr2[i]) {
											arr1[i][j] = arr2[i][j]
										}

									}

									this.tableData = arr1
									console.log(12321421, this.tableData)
									this.tableColumns = []
									this.tableColumns = [{
											prop: "USED",
											label: "CPU使用率",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "Time",
											label: "CPU使用率时间",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "user",
											label: "用户使用率",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "system",
											label: "系统使用率时间",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "wait",
											label: "CPU等待",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "USED1",
											label: "内存使用率",
											width: "",
											isShow: true,
											format: 'normal'
										},
										{
											prop: "Time1",
											label: "内存使用率时间",
											width: "",
											isShow: true,
											format: 'normal'
										},
									];
									this.fileName =
										"【" + this.postData.filters.IP + "】" + "CPU和内存使用率";
								})
								.catch((err) => {
									console.log(err);
								});
							break;
						case "FileSystemHistory":
							this.InitFileSystemHistory(this.postData.filters.IP);
							break;
					}
				}
			},
			InitFileSystemHistory(val) {
				getFileMounted({
						ip: val
					})
					.then((_) => {
						if (_.length) {
							let option = _.map((item) => {
								return {
									label: item.mountedOn,
									value: item.mountedOn,
								};
							});
							this.operaOption[1].filter.options = option;
							this.operaOption[1].filter.data = _[0].mountedOn;

							this.ChangeFileSystemHistory(this.operaOption[1].filter.data);
						} else {
							this.$message.error("无可用文件挂载点");
							this.allData = {
								USED: [],
								Time: [],
							};
							this.operaOption[1].filter.options = [];
							this.operaOption[1].filter.data = "";

							this.loading = false;
						}
					})
					.catch((_) => {});
			},
			ChangeFileSystemHistory(val) {
				this.loading = true;
				getFileSystemHistory({
						time: this.postData.filters.StartTime,
						time2: this.postData.filters.EndTime,
						holdon: val,
						ip: this.postData.filters.IP,
					})
					.then((res) => {
						this.allData = {
							USED: [],
							Time: [],
						};
						if (res) {
							this.dataTotal = res.length;
							this.allData.dataTotal = this.dataTotal;
							res.forEach((item) => {
								this.allData.USED.push(item.usedPer * 100);
								this.allData.Time.push(item.recordTime);
							});
						}
						this.loading = false;
						this.tableColumns = []
						this.tableColumns = [{
								prop: "USED",
								label: "使用率",
								width: "",
								isShow: true,
								format: 'normal'
							},
							{
								prop: "Time",
								label: "使用率时间",
								width: "",
								isShow: true,
								format: 'normal'
							},
						];
						this.tableData = this.allData.USED.map((item, index) => {
							return {
								USED: this.allData.USED[index],
								Time: this.allData.Time[index],
							};
						});
						this.fileName =
							"【" + this.postData.filters.IP + "】" + "文件系统使用率";
					})
					.catch((err) => {
						console.log(err);
					});
			},
			getPaginationCurPage(val) {
				this.postData.curPage = val;

				// this.getTableData();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				// this.getTableData();
			},
			// 获取子组件选择的时间
			getPickerDate(pickerDate) {
				this.postData.curPage = 1;
				for (const key in pickerDate) {
					this.postData.filters[key] = pickerDate[key];
				}

				// this.getTableData();
			},
			getSelectOpera(item) {
				this.postData.curPage = 1;
				this.postData.opera = item.value;
				// 删除后台可能无法识别的 filters 条件
				for (const key in this.postData.filters) {
					if (
						key != "monid" &&
						key != "StartTime" &&
						key != "EndTime" &&
						key != "fre" &&
						key != "IP"
					) {
						delete this.postData.filters[key];
					}
				}

				// this.getTableData();
			},
			//处理时间间隔
			getIntervalOpera(item) {
				this.postData.curPage = 1;
				//放时间间隔的

				// this.postData.filters[fre]=fre.value
				this.postData.curPage = 1;
				this.postData.filters.fre = item.value;

				// 删除后台可能无法识别的 filters 条件
				for (const key in this.postData.filters) {
					if (
						key != "monid" &&
						key != "StartTime" &&
						key != "EndTime" &&
						key != "fre" &&
						key != "IP"
					) {
						delete this.postData.filters[key];
					}
				}
			},
			getInputFilter(data) {
				this.postData.curPage = 1;
				for (const key in data) {
					if (data.hasOwnProperty(key)) {
						const element = data[key];
						this.postData.filters[key] = element;
					}
				}

				// this.getTableData();
			},
			exportData(data) {
				console.log(data);
				let _url = this.exportOption[data.type].url;
				let _fileName =
					"【" +
					this.seleItem.IP +
					"】" +
					this.exportOption[data.type].fileName +
					".xls";
				let _data = {
					ip: this.seleItem.IP,
					time: this.postData.filters.StartTime,
					time2: this.postData.filters.EndTime,
					fre: this.postData.filters.fre,
				};

				exportData(_url, _data)
					.then((res) => {
						downloadFile(res, _fileName);
					})
					.catch((err) => {
						this.$message.error({
							message: "导出文件失败：" + _fileName,
						});
					});
			},
			// remoteMethod(query) {
			//   if (query !== "") {
			//     this.loading = true;
			//     setTimeout(() => {
			//       this.loading = false;

			//       this.options = this.list.filter((item) => {
			//         return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
			//       });
			//     }, 200);

			//     this.postData.filters.IP = this.selectItem.IP;
			//     this.getTableData();
			//     // this.InitFileSystemHistory();
			//   } else {
			//     this.options = [];
			//   }
			// },
			selectIp() {
				this.postData.filters.IP = this.selectItem;
				// this.getTableData();
				// this.InitFileSystemHistory()
			},
		},
		watch: {
			//     loading: {
			// 　　　　handler(newValue, oldValue) {
			//             console.log("------发--------");
			//             console.log(newValue, oldValue);
			// 　　　　}
			// 　　}
		},
	};
</script>

<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.spanInfo {
		padding-right: 10px !important;
	}

	.searchIP {
		padding-bottom: 10px;
	}

	.textLable>>>.el-button+.el-button {
		margin-left: 0px !important;
	}

	.IpButton {
		width: 100%;
		font-size: 14px;
	}

	.textLable .IpButton.selected {
		color: rgb(255, 255, 255);
		background: rgb(64, 158, 255);
	}

	.All {
		height: 100%;
	}

	.spanInfo {
		height: 100%;
	}

	.All .TableInfo {
		height: calc(100% - 10px);
	}

	.TableInfo .serverContainer {
		padding: 30px;
		background: #fff;
		border: 1px solid #ddd;
		border-radius: 5px;
		height: calc(100% - 52px);
	}

	.TableInfo .serverContainer .netload {
		height: calc(100% - 20px - 30px);
	}

	.server-enter-active {
		animation: dialog 0.6s ease;
	}

	.server-leave-active {
		animation: dialog 0.6s ease reverse;
	}

	@keyframes dialog {
		from {
			transform: scale(0);
		}

		to {
			transform: scale(1);
		}
	}
</style>
